# -*-coding:utf-8 -*-
# Author : Mo
# Data : 2022/2/4 20:48
from app01 import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from app01.utils.bootstrap import BootStrapModelForm
from app01.utils.encrypt import md5


class AdminModelForm(BootStrapModelForm):

    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Admin
        fields = ["username","password","confirm_password"]
        widgets = {
            "password":forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data["password"]
        return md5(pwd)

    def clean_confirm_password(self):
        pwd = self.cleaned_data["password"]
        confirm = md5(self.cleaned_data["confirm_password"])
        if confirm != pwd:
            raise ValidationError("密码不一致")
        # 返回什么，其字段以后保存到数据库是什么
        return confirm


class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = models.Admin
        fields = ["username"]


class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.Admin
        fields = ["password", "confirm_password"]
        widgets = {
            "password": forms.PasswordInput(render_value=True)
        }

    def clean_password(self):
        pwd = self.cleaned_data["password"]
        md5_pwd = md5(pwd)

        # # 去数据库校验当前密码是否存在
        # exists = models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists()
        # if exists:
        #     raise ValidationError("密码不能与以前一致")

        return md5_pwd

    def clean_confirm_password(self):
        pwd = self.cleaned_data["password"]
        confirm = md5(self.cleaned_data["confirm_password"])
        if confirm != pwd:
            raise ValidationError("密码不一致")
        # 返回什么，其字段以后保存到数据库是什么
        return confirm


class UserModelForm(BootStrapModelForm):

    name = forms.CharField(
        min_length=3,
        label="用户名",
        widget=forms.TextInput(attrs={"class":"form-control"}),
    )

    class Meta:
        model = models.UserInfo
        fields = ["name","password","age","account","create_time","gender","depart"]


class PrettyModelForm(BootStrapModelForm):

    # 验证方式1
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        fields = "__all__"
        # fields = ["mobile","price","level","status"]
        # exclude = ['level']


    # 验证：方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            # 验证不通过
            raise ValidationError("手机号已存在")
        # 验证通过，用户输入的值返回
        return txt_mobile


class PrettyEditModelForm(forms.ModelForm):
    # mobile = forms.CharField(disabled=True,label="手机号")
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile","price","level","status"]

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {"class":"form-control","placeholder":field.label}

    def clean_mobile(self):
        # 当前编辑的ID
        # print(self.instance.pk)
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            # 验证不通过
            raise ValidationError("手机号已存在")
        # 验证通过，用户输入的值返回
        return txt_mobile